<?php

namespace app\api\controller\user;

use app\api\controller\AuthController;
use app\api\service\SignInService;
use think\facade\Queue;

class SignController extends AuthController
{
    /**
     * 用户签到
     *
     * */
    public function save()
    {
        $store_id = $this->request->param('store_id/d');

        if (empty($store_id)){
            return json(['code' => 0, 'msg' => '非法参数!']);
        }

        $user_id = $this->request->user['user_id'];

        $signIn = SignInService::getCurrentDayRecord($user_id);

        if (!empty($signIn)){
            return  json(['code' => 0, 'msg' => '您已经签到过了,明天再来吧!']);
        }

        $yesterday = SignInService::getYesterdayDayRecord($user_id);

        $total_num = 1;
        if (empty($yesterday)){
            $result = SignInService::saveSignIn($user_id,$total_num);
            return $result ? json(['code' => 1, 'msg' => '签到成功!']) : json(['code' => 0, 'msg' => '签到失败!']);
        }


        $total_num  += $yesterday['total_num'];

        $result = SignInService::saveSignIn($user_id,$total_num);

        $sign_in_config = SignInService::getStoreSignInConfig($store_id);

        $integral = $sign_in_config['sign_in_integral'];
        if (!empty($sign_in_config) && !empty($sign_in_config['sign_in_config'])){
            $config = $sign_in_config['sign_in_config'];
            $rst = array_key_exists($total_num,$config);
            if ($rst){
                $integral = $config[$total_num]['give_integral'];
                if (empty($coupons = $config[$total_num]['coupon_info'])){
                    foreach ($coupons as $c){
                        Queue::push('app\store\job\Coupon',[
                            'user_id' =>  $user_id,
                            'coupon_id' => $c['coupon_id'],
                            'num' => $c['give_num'],
                        ],'userCoupon');
                    }
                }
            }

        }

        Queue::push('app\store\job\Account@integral',[
            'user_id' => $user_id,
            'desc' => '签到奖励',
            'change_type'=> 1,
            'integral' => $integral
        ],'userAccount');


        return $result ? json(['code' => 1, 'msg' => '签到成功!']) : json(['code' => 0, 'msg' => '签到失败!']);

    }


}